import React, {useContext} from 'react';
import { Form, Input, Button, message } from 'antd';
import { postLogin } from '../../network/protocol'
import './style.less'
import Cookies from 'js-cookie';
import context from '../../redux/context'
import { Redirect } from 'react-router-dom';



const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 20 },
};
const tailLayout = {
  wrapperCol: { offset: 6, span: 16 },
};


const Login = () => {
  const {state, dispatch} = useContext(context);

  const onFinish = async values => {
    let data = await postLogin(values)
    console.log('Success:', data);
    if(data.errorCode === 0 ) {
      dispatch({type: 1})
      Cookies.set('token',data.source.token)
      window.location.hash = '/';
    } else {
      message.error(data.message)
    }
  };

  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

if(state.login) return <Redirect to={{ pathname: '/' }} />

  return <div className="login">
    <div className="login-con">

    <Form
      {...layout}
      name="basic"
      initialValues={{ userId: 'admin',userPass:'admin1234/'  }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item
        label="用户名"
        name="userId"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="userPass"
        rules={[{ required: true, message: 'Please input your password!' }]}
      >
        <Input.Password />
      </Form.Item>

      {/* <Form.Item {...tailLayout} name="remember" valuePropName="checked">
        <Checkbox>Remember me</Checkbox>
      </Form.Item> */}

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
    </div>

  </div>

}


export default Login